﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using LapvComponent;
using System.Web.Security;
using LapvBussiness;
 

namespace Lapv
{
    public partial class Login : System.Web.UI.Page
    {
        string _strUrl = "";

        public string domainStyle = ConfigLapv.Instance.DomainStyle;
        public string domain =ConfigLapv.Instance.DomainAdmin;
        LapvComponent.account us = null;
        protected void Page_Load(object sender, EventArgs e)
        {

            if (Request.Params["returnurl"] != null)
            {
                _strUrl = Request.Params["returnurl"].ToString();
            }
            if (Page.IsPostBack) return;
            string UsName = "";
            try
            {
                UsName = HttpContext.Current.User.Identity.Name.ToString();
            }
            catch { }
            if (UsName != "")
            {
                if (string.IsNullOrEmpty(_strUrl))
                {

                    if (Session["valpermission"] != null && Session["valpermission"].ToString() != "")
                    {
                        us = new account();
                        us = (account)Session["valpermission"];

                        Response.Redirect(domain);
                    }
                else Provider.CheckAuthen("");


                }
                else
                {
                    if (Session["valpermission"] != null && Session["valpermission"].ToString() != "")
                    {
                        us = new account();
                        us = (account)Session["valpermission"];

                        Response.Redirect(_strUrl);
                    }
                    else Provider.CheckAuthen("");

                }
            }
        }

        private Boolean isValidIp(String ip, String ipC)
        {
            try
            {
                if (ipC.Equals("*"))
                {
                    return true;
                }
                String _1stC, _2ndC, _3rdC, _4thC;
                //string _1stC, _4ndC;
                //string _2ndC;
                //string _3rdC;

                if (ipC.IndexOf(":") != -1)
                {
                    ipC = ipC.Substring(0, ip.IndexOf(":"));
                }
                String[] splC = ipC.Split('.');
                _1stC = splC[0];
                _2ndC = splC[1];
                _3rdC = splC[2];
                _4thC = splC[3];
                String _1st, _2nd, _3rd, _4th;
                if (ip.IndexOf(":") != -1)
                {
                    ip = ip.Substring(0, ip.IndexOf(":"));
                }
                String[] spl = ip.Split('.');
                _1st = spl[0];
                _2nd = spl[1];
                _3rd = spl[2];
                _4th = spl[3];
                //System.out.println(_1st + "-" + _2nd + "-" + _3rd + "-" + _4th);
                //System.out.println(ipCanLogin.toString());
                if (!_1stC.Equals("*") && !_1stC.Equals(_1st))
                {

                    return false;
                }

                if (!_2ndC.Equals("*") && !_2ndC.Equals(_2nd))
                {
                    return false;
                }

                if (!_3rdC.Equals("*") && !_3rdC.Equals(_3rd))
                {
                    return false;
                }
                if (!_4thC.Equals("*") && !_4thC.Equals(_4th))
                {
                    return false;
                }
                return true;
            }
            catch (Exception)
            {
                // logError("Error", e);
                return false;
            }


        }

        protected void Mylogin_Authenticate(object sender, AuthenticateEventArgs e)
        {
            
            account obj = null;

            if (Request.Params["returnurl"] != null)
            {
                //_strUrl =Request.Params["returnurl"].ToString();
                _strUrl = this.Request.RawUrl.ToString();
                if (_strUrl.Contains("Lapv"))
                    _strUrl = _strUrl.Replace("/Lapv/Login.aspx?returnurl=", "");
                else
                    _strUrl = _strUrl.Replace("/Login.aspx?returnurl=", "");
                _strUrl = HttpUtility.UrlDecode(_strUrl);
            }
            int timelogin = int.Parse(DateTime.Now.Hour.ToString());
            string ipAd = Request.UserHostAddress.ToString();
            string iplogin = "";
            System.Web.UI.WebControls.Login mylg = (System.Web.UI.WebControls.Login)LoginView1.FindControl("Mylogin");
            Label lbl = (Label)mylg.FindControl("lblNoti");
            lbl.Text = "";
            if (mylg.UserName != "" && mylg.Password != "")
            {
                try
                {
                    string un = mylg.UserName.ToLower();
                    string pass =  Provider.GetMD5Hash(mylg.Password);
                    string ips = "";
                    string appid = HttpContext.Current.Request.UserHostName;
                    using (lapvEntities db = new lapvEntities())
                    {
                        obj = db.accounts.Include("role1").Where(ec => ec.username == un && ec.password == pass && ec.starthour <= timelogin && ec.endhour >= timelogin).FirstOrDefault();
                        if (obj != null)
                        {
                            ips = obj.ipcanlogin;
                        }
                    }
                    if (obj != null)
                    {

                        Session["valpermission"] = obj;//.role.ToString();
                        iplogin = obj.ipcanlogin.ToString();
                        if (iplogin != "")
                        {

                            if ((!ips.Contains("," + appid + ",")) && ips != "*")
                            {
                                ((Lapv)this.Master).MessageWarning = "Bạn không có quyền đăng nhập với ip này";
                                return;
                            }
                            else
                            {
                                e.Authenticated = true;
                                FormsAuthentication.SetAuthCookie(mylg.UserName, false);
                                //Response.Cookies.Clear();
                                //DateTime expiryDate = DateTime.Now.AddMinutes(60);                               
                                //FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2, mylg.UserName.Trim(), DateTime.Now, expiryDate, true, String.Empty);
                                //string encryptedTicket = FormsAuthentication.Encrypt(ticket);
                                //HttpCookie authenticationCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                                //authenticationCookie.Expires = ticket.Expiration;                                
                                //Response.Cookies.Add(authenticationCookie);
                                Session["UserId"] = obj.id;
                                Session["UserName"] = obj.username;
                                Session["Role"] = obj.role1.id;

                            }

                        }



                        if (string.IsNullOrEmpty(_strUrl))
                        {
                            Response.Redirect(domain + "default.aspx");


                        }
                        else
                        {

                            Response.Redirect(_strUrl);


                        }
                        //if (Session["valpermission"] != null)

                    }
                    else
                    {

                        ((Lapv)this.Master).MessageError = "Tài khoản không tồn tại, hoặc mật khẩu sai";
                    }
                }
                catch (Exception ex)
                {

                    ((Lapv)this.Master).MessageError = "Đăng nhập lỗi" + ex.Message;
                }






            }
        }
    }
}
